<template>
  <el-container>
    <div class="row_block">
      <el-card class="box-card" style="width: 800px">
        <div slot="header" class="clearfix">
          <el-button type="shenda" size="small" icon="el-icon-back" style="float: right" @click="goBack">返回</el-button>
          <span>批量入库</span>

        </div>
        <el-form :model="form" ref="form" :rules="rules" label-width="150px">
          <el-form-item label="上游公司" prop="channelCompany">
            <el-select size="small" placeholder="上游公司" v-model="form.channelCompany" @change="changeChannelCompany"
                       style="width: 300px;">
              <el-option v-for="item in form.channelcompanyListSelect" :key="item.value" :label="item.label"
                         :value="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="上传方式" prop="dictCardOperator">
            <el-radio-group v-model="form.dictCardOperator" @change="changeOperator">
              <!--              <el-radio label="CARDTELECOM">电信</el-radio>
                            <el-radio label="CARDMOBILE">移动</el-radio>-->
              <el-radio label="CARDUNICOM">联通上传</el-radio>
              <el-radio label="FLOWPOOL">通用上传</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="更新方式" prop="updateMethod">
            <el-radio-group v-model="form.updateMethod">
              <!--              <el-radio label="CARDTELECOM">电信</el-radio>
                            <el-radio label="CARDMOBILE">移动</el-radio>-->
              <el-radio label="insertNew">新增</el-radio>
              <el-radio label="updateNew">根据ICCID更新字段信息</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="卡号类型" prop="cardNumberType"
                        v-if="form.dictCardOperator!=='FLOWPOOL'"
                        style="width: 600px">
            <el-select size="small" style="width: 300px;" v-model="form.cardNumberType">
              <el-option label="去掉末尾数字" value="1"></el-option>
              <el-option label="EXCEL第二列" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择账号" prop="accountId">
            <el-select size="small" placeholder="选择账号" style="width: 300px;" v-model="form.accountId">
              <el-option v-for="account in form.accountSelect" :key="account.id" :label="account.accountName"
                         :value="account.id"></el-option>
            </el-select>
          </el-form-item>
          <!--          <el-form-item label="卡状态" prop="dictChannelCardStatus" v-if="(dictOperator==='TELECOM' || dictOperator==='XIAOXIANG')&&form.dictCardOperator!=='FLOWPOOL'" style="width: 600px">
                      <el-radio-group v-model="form.dictChannelCardStatus">
                        <el-radio label="ACTIVATE">已激活</el-radio>
                        <el-radio label="DEACTIVATE">去激活</el-radio>
                      </el-radio-group>
                    </el-form-item>-->
          <el-form-item label="上传卡号" prop="fileName"
                       >
            <el-upload
              class="upload-demo"
              action="#"
              :before-upload="uploadCards"
              :limit="1">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">{{ form.fileName }}</div>
            </el-upload>
            <el-button type="success" @click="getModulLT" size="small"
                       v-if="form.channelCompany.label.indexOf('联通') > -1">
              下载联通摸板
            </el-button>
            <!--            <el-button type="success" @click="getModulDX" size="small" v-if="form.channelCompany.dictOperator==='CMPTELECOM'">下载电信CMP摸板</el-button>-->
            <el-button type="shenda" size="small" @click="downLoadShuolangMuban" :loading="loading"
                       v-if="form.dictCardOperator=='FLOWPOOL'"> 下载导入模板<i class="el-icon-download el-icon--right"></i>
            </el-button>
          </el-form-item>

          <!--          <el-form-item label="起始业务号码" prop="insNumber"
                                  v-if="form.channelCompany.dictOperator!=='UNICOM'&&form.channelCompany.dictOperator!=='CMPTELECOM'&&form.channelCompany.dictOperator!=='LIANTONGWULIAN'&&form.dictCardOperator!=='FLOWPOOL'&&form.channelCompany.dictOperator!=='LIANTONGJIYUEHUA'">
                      <el-input v-model.trim="form.insNumber" type="text" min="0" max="2147483648"
                                style="width: 300px"></el-input>
                    </el-form-item>
                    <el-form-item label="apn" prop="apn"
                                  v-show="form.channelCompany.dictOperator!=='UNICOM'&&form.channelCompany.dictOperator!=='CMPTELECOM'&&form.channelCompany.dictOperator!=='LIANTONGWULIAN'&&form.dictCardOperator!=='FLOWPOOL'&&form.channelCompany.dictOperator!=='LIANTONGJIYUEHUA'">
                      <el-input size="small" style="width: 300px;" v-model="form.apn"></el-input>
                    </el-form-item>-->

          <el-form-item>
            <el-button type="primary" v-preventReClick @click="submitHandles('form')">提交</el-button>
            <el-button v-preventReClick @click="resetForm('form')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </el-container>
</template>

<script>
import {singleCardStorage, batchInventory, batchInventoryUnicom, listAccountByChannelCompanyId} from '@/api/getData'

export default {
  name: 'BatchStockIndex',
  data() {
    return {
      pagekey: '',
      rules: {
        channelCompany: [{required: true, message: '请选择上游公司',}],
        bodyType: [{required: true, message: '请选择卡体类型',}],
        accountId: [{required: true, message: '请选择账号',}],
        cardNumberType: [{required: true, message: '卡号类型',}],
      },
      dictChannelCardStatus: 'ACTIVATE',
      form: {
        channelCompany: {label:''},
        bodyType: '',
        bodyTypeSelect: [],
        channelcompanyList: [],
        channelcompanyListSelect: [],
        nowData: '',
        numRules: [],
        numRulesSelect: [],
        startIccId: '',
        endIccId: '',
        primeval: '',
        endLetter: '',
        preLetter: '',
        dictChoseDirect: '',
        dictCardType: '',
        typeOneStartIccId: '',
        typeOneEndIccId: '',
        typeTwoStartIccId: '',
        typeTwoEndIccId: '',
        dictChannelCardStatus: 'DEACTIVATE',
        accountSelect: [],
        accountId: '',
        quietPeriodDate: '',
        insNumber: '',
        unit: "G",
        dictCardOperator: 'CARDTELECOM',
        apn: "",
        dateType: '',
        type: "1",
        fileName: '',
        updateMethod: 'insertNew'
      },
      active: 1,
      dictOperatorName: '',
      currentNum: '',
      endIccId: '',
      dictOperator: '',
      errorReason: '',
      loading: false,
      unitSelect: [
        {
          value: 'G',
          label: 'GB'
        },
        {
          value: 'M',
          label: 'MB'
        }
      ],

    }
  },
  async created() {
    this.pagekey = await this.$getPageKey();
    this.initData();

  },

  methods: {
    goBack() {
      this.$router.back(-1)
    },
    submitHandles(form) {
      this.errorReason = '';
      let mb = 0;
      if (this.form.unit === 'G') {
        mb = this.form.primeval * 1024
      } else {
        mb = this.form.primeval
      }

      let channelCompanyId = this.form.channelCompany.value;
      this.$refs[form].validate(async (valid) => {
        if (valid) {
          let cardNumberType = this.form.dictCardOperator === "CARDUNICOM" ? this.form.cardNumberType : '';
          let startIccId = this.form.type == 1 ? this.form.typeOneStartIccId : this.form.typeTwoStartIccId;
          let endIccId = this.form.type == 1 ? this.form.typeOneEndIccId : this.form.typeTwoEndIccId;

          let params = {
            channelCompanyId: channelCompanyId,
            dictCardOperator: this.form.dictCardOperator,
            accountId: this.form.accountId,
          };
          if (this.form.dictCardOperator !== 'FLOWPOOL') {
            params.dictCardBodyType = this.form.bodyType
            params.dictCardType = this.form.dictCardType
            params.dictChoseDirect = this.form.dictChoseDirect
            params.primeval = mb
            params.quietPeriodDateStr = this.form.nowData + ' 23:59:59'
            params.cardNumberType = cardNumberType
            params.beginIccId = startIccId
            params.finalIccId = endIccId
            params.type = this.form.type
            params.endLetter = this.form.endIccId
            params.preLetter = this.form.preLetter
            params.dictChannelCardStatus = this.form.dictChannelCardStatus
            params.insNumber = this.form.insNumber
            params.apn = this.form.apn

          }
          params.updateMethod = this.form.updateMethod
          if (this.form.file !== undefined && this.form.file) {
            params.file = this.form.file
          } else if ((this.form.channelCompany.value === '14' || this.form.dictCardOperator == 'FLOWPOOL') && !this.form.file) {
            this.$alert('请选择Excel文件', '提示', {
              confirmButtonText: '确定',
              callback: action => {

              }
            });
            return false;
          }
          //测试  联通执行小宇新接口
          batchInventoryUnicom(params, {
            pagekey: this.pagekey
          }).then(b=>{
            if (b._result) {
              this.$confirm('数据已提交，批量入库中， 是否立即跳转至入库记录查看结果?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                this.$router.push({
                  path: '/Stock/stockInList'
                })
              }).catch(() => {
                this.resetForm(form);
              });
            }
          });


          this.pagekey = await this.$getPageKey();
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.form.typeOneStartIccId = '';
      this.form.typeOneEndIccId = '';
      this.form.endIccId = '';
      this.form.typeTwoStartIccId = '';
      this.form.typeTwoEndIccId = '';
      this.form.preLetter = '';
      this.form.channelCompany = {};
      this.form.nowData = this.dateFormate.formate(0);
      this.form.unit = 'G';
      this.$refs[formName].resetFields();
    },

    //切换静默期
    changeDateType(val) {
      this.form.dateType = val;
      this.form.nowData = this.dateFormate.formate(parseInt(val));
    },
    async initData() {
      const returnData = await singleCardStorage({})
      if (returnData._result) {
        returnData.data.channelcompanyList.forEach(item => {
          this.form.channelcompanyListSelect.push({
            value: item.id,
            label: item.operatorBranch,
            dictOperator: item.dictOperator
          })
        });
        for (let s in returnData.data.bodyType) {
          this.form.bodyTypeSelect.push({value: s, label: returnData.data.bodyType[s]})
        }
        this.form.nowData = returnData.data.nowData;
        if (returnData.data.numRules) {
          returnData.data.numRules.forEach(item => {
            this.form.numRulesSelect.push({id: item.id, name: item.name})
          })
        }
      }
    },


    async changeChannelCompany(val) {
      this.$refs['form'].clearValidate();
      this.form.accountId = '';
      this.form.channelCompany = val;
      let list = await listAccountByChannelCompanyId({
        channelCompanyId: val.value
      });
      if (list._result) {
        this.form.accountSelect = list.data
      }
      if (val.label.indexOf('联通') > -1) {
        this.form.dictCardOperator = 'CARDUNICOM';
      } else {
        this.form.dictCardOperator = 'FLOWPOOL';
      }

    },

    uploadCards(file) {
      this.form.file = file;
      if (file) {
        this.form.fileName = file.name;
      }
    },
    getModulLT() {
      window.location.href = 'https://imgsd.1688iot.vip/unicom_template.xlsx';
    },
    getModulDX() {
      window.location.href = 'https://imgsd.1688iot.vip/%E7%94%B5%E4%BF%A1CMP%E5%85%A5%E5%BA%93%E6%A8%A1%E6%9D%BF.xlsx';
    },
    changeOperator(val) {
      console.log(this.form.channelCompany.label.indexOf('联通') > -1)
      if (val == 'FLOWPOOL' && this.form.channelCompany.label.indexOf('联通') > -1) {
        this.$message.error("选择错误！联通通道只能选择联通上传！")
        this.form.dictCardOperator = 'CARDUNICOM'
        return
      }
      this.form.dictCardOperator = val;
      // this.form.channelCompany = {};
      for (let item of this.form.channelcompanyListSelect) {
        if (val === 'CARDUNICOM' && item.label.indexOf('联通') > -1) {
          this.changeChannelCompany(item);
          break;
        }
        /* else if (val === 'FLOWPOOL' && item.label.indexOf('岱川') > -1) {
           this.changeChannelCompany(item);
           break;
         }*/
      }

    },
    downLoadShuolangMuban() {
      let href = "https://imgsd.1688iot.vip/tongyong_temp.xlsx";
      window.open(href, '_blank');
    },
    keyChangeHandle(fileList) {
      if (fileList !== '') {
        return false
      } else {
        this.fileList.excel = this.$refs.key.files[0]
        if (this.$refs.key.files[0] != null) {
          this.fileName = this.$refs.key.files[0].name;
          this.fileType = this.fileName.substring(this.fileName.lastIndexOf('.') + 1, this.fileName.length);
        }
      }
    },
  }
}
</script>

<style scoped lang="scss">
.link_class {
  color: #1890ff;
  cursor: pointer;
}

.el-header {
  margin-top: 5vh;
}

.el-main {
  .el-form {
    .button /deep/ .el-col {
      display: flex;
      justify-content: flex-start;
    }

    .box /deep/ label {
      text-align: left;
    }

    .sale /deep/ label {
      letter-spacing: 7px;
    }
  }
}

.el-popper[x-placement^=top] {
  box-shadow: 0px 0px 10px #888888;
  margin-left: 6px;
  margin-right: -39px;

  button {
    display: block;
  }

  .operation {
    border: 0;
    outline: none;
    display: block;
    text-align: center;
    margin: 0;
  }
}

.file_upload_box {
  display: inline-block;
  width: 200px;
  height: auto;
  position: relative;
  overflow: hidden;
}

.file_upload_box input[type=file] {
  position: absolute;
  left: 0;
  top: 6px;
  width: 100px;
  line-height: 25px;
  opacity: 0;
  cursor: pointer;
}

.file_upload_box a {
  display: inline-block;
  width: 50%;
  line-height: 25px;
  text-align: center;
  font-family: "Microsoft yahei";
  background-color: #315baf;
  color: #FFF;
  font-weight: 700;
  text-decoration: none;
}

.row_block {
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 70px 0;
}
</style>
